import bowser from 'bowser';
/**
 * @description 获取浏览器信息
 */
export function getBrowserCustom(): { name: string; version: string } {
  const ua = window?.navigator?.userAgent
  if (!ua) throw new Error('无法获取浏览器信息')
  // console.log(ua)
  // Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36

  let browserName
  let browserVersion
  if (ua.indexOf('MSIE') > -1 || ua.indexOf('Trident/') > -1) {
    browserName = 'Internet Explorer'
    browserVersion = ua.match(/(?:MSIE |rv:)(\d+(\.\d+)?(\.\d+)?(\.\d+)?)/)[1]
  } else if (ua.indexOf('Edg/') > -1) {
    browserName = 'Microsoft Edge'
    browserVersion = ua.match(/Edg\/(\d+(\.\d+)?(\.\d+)?(\.\d+)?)/)[1]
  } else if (ua.indexOf('QQBrowser/') > -1) {
    browserName = 'QQ浏览器'
    browserVersion = ua.match(/QQBrowser\/(\d+(\.\d+)?(\.\d+)?(\.\d+)?)/)[1]
  } else if (ua.indexOf('Firefox') > -1) {
    browserName = 'Firefox'
    browserVersion = ua.match(/Firefox\/(\d+(\.\d+)?(\.\d+)?(\.\d+)?)/)[1]
  } else if (ua.indexOf('Chrome') > -1 && ua.indexOf('Safari') > -1) {
    browserName = 'Chrome'
    browserVersion = ua.match(/(?:Chrome|Chromium)\/(\d+(\.\d+)?(\.\d+)?(\.\d+)?)/)[1]
  } else if (ua.indexOf('Opera') > -1 || ua.indexOf('OPR/') > -1) {
    browserName = 'Opera'
    browserVersion = ua.match(/(?:Opera|OPR)\/(\d+(\.\d+)?(\.\d+)?(\.\d+)?)/)[1]
  } else if (ua.indexOf('Safari') > -1 && ua.indexOf('Chrome') === -1) {
    browserName = 'Safari'
    browserVersion = ua.match(/Version\/(\d+(\.\d+)?(\.\d+)?(\.\d+)?)/)[1]
  } else {
    browserName = 'Unknown'
    browserVersion = 'Unknown'
  }

  return {
    name: browserName,
    version: browserVersion
  }
}


/**
 * @description 获取浏览器信息
 */
export function getBrowser<T>(customFunc?: (bowser) => T): T {
  if (customFunc && typeof customFunc === 'function') return customFunc(bowser)
  else if (customFunc) throw new Error('getBrowser custom func is not function')
  const ua = window?.navigator?.userAgent
  if (!ua) throw new Error('无法获取浏览器信息')
  return bowser?.parse(ua) as T;
}
